//
//  FindPartTableViewController.swift
//  TwERP2017
//
//  Created by Li Xiangyang on 22/06/2017.
//  Copyright © 2017 Li Xiangyang. All rights reserved.
//

import UIKit

class FindPartTableViewController: UITableViewController,UISearchBarDelegate {

    
    
    @IBOutlet var doubleTap: UITapGestureRecognizer!
    @IBOutlet var itemListView: UITableView!
   
    
    var gdVTC : DetailViewController?
    var itemList = [TwERPPartItem]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        itemListView.addGestureRecognizer(doubleTap)
        
     
    }

    @IBAction func addItem(_ sender: Any) {
        if ( self.itemList.count == 0) {return}
        
        if let indexPath = itemListView.indexPathForSelectedRow {
            
            let lbItem = itemList[indexPath.row]
            
            var hintMsg = ""
            
            if  (gdVTC?.gongdanBeginEdit())!{
                lbItem.quantity = 1
             
                gdVTC?.gongdan?.addPartItem(lbItem)
                gdVTC?.refreshServiceItems()
                hintMsg = "配件已添加，可返回查看修改或继续添加!"
            }else {
                hintMsg = "该工单不可修改!"
            }
            let alert =  UIAlertController(title: "提示", message: hintMsg, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){}
        }

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return itemList.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     
        let cell = tableView.dequeueReusableCell(withIdentifier: "Find Part", for: indexPath)
        
        // Configure the cell...
        let lItem = itemList[indexPath.row]
        cell.textLabel?.text = lItem.partName
        
        cell.accessoryType = UITableViewCellAccessoryType.none
        cell.detailTextLabel?.text = String(format: "%1.2f",(lItem.price))
            
        
        return cell
        
    }
    
    
    func startActivityIndicating ()
    {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        indicator.stopAnimating()
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: indicator)
        
    }
    
    func stopActivityIndicating ()
    {
        navigationItem.rightBarButtonItem = nil
        
    }

    func searchBy(keyword :String) -> Void {
        
        startActivityIndicating()
        
        
        DispatchQueue.global(qos: .userInitiated).async {
            
            let tmpItemList = TwERPPartItem.parts(withKeyword: keyword)
            
            
            DispatchQueue.main.async {
                self.stopActivityIndicating()
                if tmpItemList == nil || tmpItemList?.count == 0 {
                    let alert =  UIAlertController(title: "提示", message: "未找到相关配件！", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
                    self.present(alert, animated: true){}
                } else {
                    self.itemList = tmpItemList! as! [TwERPPartItem]
                    self.itemListView.reloadData()
                    
                }
                
            }
        }
        
        
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBy(keyword: searchBar.text!)
    }
  
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
